import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo, type UserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = ref(!!token.value)
  
  /**
   * 登录
   */
  const handleLogin = async (username: string, password: string) => {
    try {
      const res: any = await login({ username, password })
      
      if (res.data.code === 200) {
        // 保存 token
        token.value = res.data.data.token
        localStorage.setItem('token', res.data.data.token)
        
        // 更新登录状态
        isLoggedIn.value = true
        
        // 获取用户信息
        await fetchUserInfo()
        
        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: res.data.message || '登录失败' }
      }
    } catch (error: any) {
      console.error('登录失败:', error)
      return { success: false, message: error.message || '登录失败，请重试' }
    }
  }
  
  /**
   * 获取用户信息
   */
  const fetchUserInfo = async () => {
    try {
      const res: any = await getUserInfo()
      if (res.data.code === 200) {
        userInfo.value = res.data.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  
  /**
   * 退出登录
   */
  const logout = () => {
    token.value = ''
    userInfo.value = null
    isLoggedIn.value = false
    localStorage.removeItem('token')
  }
  
  // 返回状态和方法
  return {
    token,
    userInfo,
    isLoggedIn,
    handleLogin,
    fetchUserInfo,
    logout
  }
})